package com.aaa.vegetablemarketexpress.timertask;

import com.aaa.vegetablemarketexpress.dao.OrderActDao;
import com.aaa.vegetablemarketexpress.entity.OrderAct;
import com.aaa.vegetablemarketexpress.service.OrderService;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @FileName: TimerUpdateOrderStatus
 * @Description:
 * @Author: qxh
 * @CreateTime: 2025/9/22 20:15
 * @Version: 1.0.0
 */
@Component
@EnableScheduling//启动定时任务
@Log4j2
public class TimerUpdateOrderStatus {

    @Resource
    private OrderActDao orderActDao;
    /**
     * 定时任务： 定时查询超时订单并且修改状态
     */
    @Scheduled(cron = "0 0/1 * * * ?")//每分钟执行一次
    public void updateOrderStatus() {
        log.info("定时任务开始执行：更新订单状态");
        //获取当前时间
        Date now = new Date();
        //实例化查询参数
        OrderAct orderAct = new OrderAct();
        //订单状态为0为待支付
        orderAct.setActno(0);
        //查询未支付的订单
        List<OrderAct> orderActs = orderActDao.selectOrderActs(orderAct);
        if (!CollectionUtils.isEmpty(orderActs)){
            for (OrderAct orderAct1 : orderActs) {
                //判断订单是否超时，获取下单时间和当前时间做对比
                //获取下单时间
                Date orderTime = orderAct1.getCztime();
                //看是否超时（超过30分钟
                if (now.getTime() - orderTime.getTime() > 30 * 60 * 1000) {
                    //超时,修改订单状态为无效订单
                    orderAct1.setActno(5);
                    orderAct1.setRemark("订单已超时");
                    //修改订单状态
                    orderActDao.updateOrderAct(orderAct1);
                }
            }
        }

        log.info("定时任务结束执行：更新订单状态");
    }
}
